package com.gongpingjialoan.network;

import android.text.TextUtils;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.gongpingjialoan.data.KCookie;
import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.utility.OkHttpStack;
import com.gongpingjialoan.utility.PreferenceUtils;
import com.squareup.okhttp.OkHttpClient;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * Created by Administrator on 2015/9/16.
 */
public class NetUtils {

    //请求队列
    private RequestQueue requestQuene;

    private static NetUtils instance = null;

    private PreferenceUtils mPreferenceUtils;

    private Set<String> tagUrls;

    /**
     * 私有默认构造子
     */
    private NetUtils(){
        tagUrls = new HashSet<String>();
        requestQuene = Volley.newRequestQueue(GPJApplication.getInstance() , new OkHttpStack(new OkHttpClient()));
        mPreferenceUtils = new PreferenceUtils(GPJApplication.getInstance());
    }


    /*
      获取所有的请求tag
     */
    public Set<String> getAllRequsets(){
        return  tagUrls;
    }


    /**
     * 取消所有的任务
     */
    public void cancleAllTask(){
        if(requestQuene!= null){
            for( Iterator it = tagUrls.iterator(); it.hasNext(); )
            {
                String tag = (String)it.next();
                if(!TextUtils.isEmpty(tag)) {
                    requestQuene.cancelAll(tag);
                }
            }
        }
    }


    public static NetUtils getInstance() {
        if (null == instance) {
            synchronized (NetUtils.class) {
                if (null == instance) {
                    instance = new NetUtils();
                }
            }
        }
        return instance;
    }

    /**
     * 返回请求队列
     * @return
     */
    public RequestQueue getRequestQueue() {
        return requestQuene;
    }

    /**
     * 保存cookie
     * @param cookie
     */
    public void setLocalCookie(KCookie cookie) {
        mPreferenceUtils.saveObject(cookie);
    }


    public String getLocalCookie() {
        KCookie cookie = mPreferenceUtils.loadObject(KCookie.class);
        if (null == cookie.name || null == cookie.value) {
            return null;
        } else {
            return cookie.name + "=" + cookie.value;
        }
    }

}
